<%@  language="VBScript" %>
<%  Option Explicit %>

<!--#include file="adovbs.inc"-->
<!--#include file="aspuploader/include_aspuploader.asp" -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
   <!-- <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="-1" />-->
    <title>Photos Albums</title>
    <link rel="stylesheet" type="text/css" href="MainCSS.css" />
    <link href="demo.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="styles/jquery.lightbox-0.5.css" />
    <!--<link rel="stylesheet" type="text/css" href="styles/jquery-ui.css" />-->

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <!--<script type="text/javascript" src="js/jquery.js"></script>-->

    <script type="text/javascript" src="js/jquery-ui.js"></script>
    <script type="text/javascript" src="js/jquery.lightbox-0.5.min.js"></script>
    <script type="text/javascript" src="js/jquery.ba-bbq.min.js"></script>

    <script type="text/javascript">

        var currentTab = 0;
        var i_albumid;
        var s_albumname;
        var s_username;
        var fileArray = [];
        var newAlbumid;
        var isCreatingAlbum = false;

        /************************ pop up a division ************************/
        function openPopup_click(divName, divWidth, albumId, username, resultDiv, albumName) {
            i_albumid = albumId;
            s_albumname = albumName;
            s_username = username;
            var table = document.getElementById("filelist");
            while (table.firstChild) table.removeChild(table.firstChild);
            var btn = document.getElementById("AddNewPhotos");
            btn.style.visibility = "hidden";

            var mainShade = document.getElementById("oFilterDIV");
            mainShade.style.height = "99%";
            var UploaderDiv = document.getElementById(divName);

            // Finding the current cordinate (x,y) of the top-left corner of the screen after user scroll it.
            var scrOfX = 0, scrOfY = 0; // define the current x, y offset of the screen.
            if (typeof (window.pageYOffset) == 'number') {
                //Netscape compliant   
                scrOfY = window.pageYOffset;
                scrOfX = window.pageXOffset;
            } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                //DOM compliant
                scrOfY = document.body.scrollTop;
                scrOfX = document.body.scrollLeft;
            } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
                scrOfX = document.documentElement.scrollLeft;

            }

            // end of finding the current cordinate (x,y).

            var top = scrOfY + 50;
            var left = 300;//(screen.width - divWidth) / 2;            
            top += "px";
            left += "px";
            mainShade.style.visibility = "visible";
            UploaderDiv.style.left = left;
            UploaderDiv.style.top = top;
            UploaderDiv.style.visibility = "visible";
       
        }
        
        //-------------------------------------------------------
        // Update       : 15/12/2010 NP        
        // Description  : Display Message with button [Continue].
        //                Disable other buttons    
        // History      : Remove button [Continue]. 
        //-------------------------------------------------------
        function openMessage_click(divName, divWidth) {
            $("#MessageDiv").show();
            $("#uploadTip").hide();
        }
        
        function closePopup_click(divName) {
            bpopup = "0";
            var mainShade = document.getElementById("oFilterDIV");
            var UploaderDiv = document.getElementById(divName);
            mainShade.style.visibility = "hidden";
            mainShade.style.height = "760px";
            UploaderDiv.style.visibility = "hidden";
            var btn = document.getElementById("AddNewPhotos");
            btn.style.visibility = "hidden";
            // NGUYENPTV edited at 23/NOV/2010
            //window.close();
            displayPhotos(i_albumid, s_username, 'photoDiv', s_albumname);
            $("#MessageDiv").hide();
            $("#uploadTip").show();
        }
        
        //-------------------------------------------------------
        // Update       : 05/12/2010 NP        
        // Description  : Hide Message and button [Continue].
        //                Enable other buttons    
        //-------------------------------------------------------
        function closeMessage_click(divName) {
            $("#MessageDiv").hide();
            $('#AddNewPhotos').attr('disabled', false);
            $('#uploadbutton').attr('disabled', false);
            $('#closebutton').attr('disabled', false);
        }
        
        function getScrollY() {
            var scrOfY = 0;
            if (typeof (window.pageYOffset) == 'number') {
                //Netscape compliant
                scrOfY = window.pageYOffset;
            } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                //DOM compliant
                scrOfY = document.body.scrollTop;
            } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
            }
            return scrOfY;
        }

        function getScrollX() {
            var scrOfX = 0;
            if (typeof (window.pageXOffset) == 'number') {
                //Netscape compliant
                scrOfX = window.pageXOffset;
            } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                //DOM compliant
                scrOfX = document.body.scrollLeft;
            } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                //IE6 standards compliant mode
                scrOfX = document.documentElement.scrollLeft;
            }
            return scrOfX;
        }
        /**************************** end of pop up a division ***********************/

        /********************************Common functions ****************************/
        function gup(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null) return "";
            else return results[1];
        }

        /********************************End Common functions ************************/


        /************************************Uploader *******************************/

        var handlerurl = 'ajax-handler.asp'



        function CreateAjaxRequest() {
            var xh;
            if (window.XMLHttpRequest)
                xh = new window.XMLHttpRequest();
            else
                xh = new ActiveXObject("Microsoft.XMLHTTP");

            xh.open("POST", handlerurl, false, null, null);
            xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            return xh;
        }

        function ShowAttachmentsTable() {
            var table = document.getElementById("filelist");
            while (table.firstChild) table.removeChild(table.firstChild);

            AppendToFileList(fileArray);

        }
        function AppendToFileList(list) {
            var table = document.getElementById("filelist");

            var btn = document.getElementById("AddNewPhotos");
            if (fileArray.length > 0) {
                btn.style.visibility = "visible";
            }
            else btn.style.visibility = "hidden";

            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                var row = table.insertRow(-1);
                row.setAttribute("fileguid", item.FileGuid);
                row.setAttribute("filename", item.FileName);
                var td1 = row.insertCell(-1);
                td1.innerHTML = "<img src='aspuploader/resources/circle.png' border='0'/>";
                var td2 = row.insertCell(-1);
                td2.innerHTML = "<span style='color:black'>" + item.FileName + "</span>";
                var td4 = row.insertCell(-1);

                td4.innerHTML = "<span style='color:black'>[<a href='javascript:void(0)' style='text-decoration:underline; color:blue' onclick='Attachment_Remove(this)'>remove</a>]</span>";
            }


        }

        function Attachment_FindRow(element) {
            while (true) {
                if (element.nodeName == "TR")
                    return element;
                element = element.parentNode;
            }
        }

        function Attachment_Remove(link) {
            var row = Attachment_FindRow(link);
            if (!confirm("Are you sure you want to delete '" + row.getAttribute("filename") + "'?"))
                return;

            var guid = row.getAttribute("fileguid");

            var xh = CreateAjaxRequest();
            xh.send("delete=" + guid);

            var table = document.getElementById("filelist");
            table.deleteRow(row.rowIndex);

            for (var i = 0; i < fileArray.length; i++) {
                if (fileArray[i].FileGuid == guid) {
                    fileArray.splice(i, 1);
                    break;
                }
            }

            var btn = document.getElementById("AddNewPhotos");
            if (fileArray.length > 0) {
                btn.style.visibility = "visible";
            }
            else btn.style.visibility = "hidden";

        }
        function CuteWebUI_AjaxUploader_OnPostback() {

            var uploader = document.getElementById("myuploader");
            var guidlist = uploader.value;

            var xh = CreateAjaxRequest();
            //xh.send("guidlist=" + s_username + "/" + i_albumid + "/" + guidlist);
            xh.send("guidlist=" + guidlist);
            //call uploader to clear the client state
            openMessage_click("MessageDiv", 260);
            uploader.reset();

            if (xh.status != 200) {
                alert("http error " + xh.status);
                setTimeout(function() { document.write(xh.responseText); }, 10);
                return;
            }


            var list = eval(xh.responseText); //get JSON objects

            fileArray = fileArray.concat(list);


            AppendToFileList(list);

        }

        function ShowFiles() {
            var msgs = [];
            for (var i = 0; i < fileArray.length; i++) {
                msgs.push(fileArray[i].FileName);
            }
            alert(msgs.join("\r\n"));
        }

        function ConvertArrToStr(arr) {
            var msgs = [];
            for (var i = 0; i < arr.length; i++) {
                msgs.push(arr[i].FileGuid);
            }
            return msgs.join("$");
        }

        function AddFilesToDB() {

            var xh = CreateAjaxRequest();

            xh.send("AddFilesToDB=" + s_username + "/" + i_albumid + "/" + ConvertArrToStr(fileArray)) + "&random=" + Math.random();

            if (xh.status != 200) {
                alert("http error " + xh.status);
                setTimeout(function () { document.write(xh.responseText); }, 10);
                return;
            } else {
                if (isCreatingAlbum) {
                    //$('#album' + newAlbumid + ' > div > img').attr('src', xh.responseText);
                    window.location.reload();
                }
                alert("Add New Photo(s) To Your Album completely");
                closePopup_click('UploaderDiv');
            }

        }
        //VT
        function addPhoto(str) {

            var xh = CreateAjaxRequest();
            xh.send("addPhoto=" + str);

        }

        function CuteWebUI_AjaxUploader_OnTaskComplete(task) {
            //addPhoto( s_username + "/" + task.FileName + "/" + i_albumid );


            //alert("Update Complete!");

        }

        function ShowPhotos(albumID, s_uname) {
            var table = document.getElementById("filelist");

            while (table.firstChild) table.removeChild(table.firstChild);

            //var myuploaderButton = document.getElementById("myuploaderButton");



            if (albumID != '-1') {
                //myuploaderButton.disabled =false;


                var xh = CreateAjaxRequest();

                xh.send("ShowPhotos=" + s_uname + "/" + albumID);



                if (xh.status != 200) {
                    alert("http error " + xh.status);
                    setTimeout(function() { document.write(xh.responseText); }, 10);
                    return;
                }

                var list = eval(xh.responseText); //get JSON objects

                fileArray = fileArray.concat(list);

                AppendToFileList(list);


            }
            else {
                //myuploaderButton.disabled =true; 	
                var table = document.getElementById("filelist");
                while (table.firstChild) table.removeChild(table.firstChild);
            }
            return true;
        }

        function OnChange(dropdown) {
            var newalbumname = document.getElementById("newalbumname");

            var myindex = dropdown.selectedIndex

            i_albumid = dropdown.options[myindex].value

            var table = document.getElementById("filelist");
            while (table.firstChild) table.removeChild(table.firstChild);



            if (i_albumid != '-1') {
                newalbumname.disabled = true;
                //myuploaderButton.disabled =false;
                var xh = CreateAjaxRequest();

                xh.send("OnChange=" + s_username + "/" + i_albumid);



                if (xh.status != 200) {
                    alert("http error " + xh.status);
                    setTimeout(function() { document.write(xh.responseText); }, 10);
                    return;
                }

                if (xh.responseText != "nothing") {
                    var list = eval(xh.responseText); //get JSON objects

                    fileArray = fileArray.concat(list);

                    AppendToFileList(list);
                }
                else while (table.firstChild) table.removeChild(table.firstChild);



            }
            else {
                //myuploaderButton.disabled =true;
                newalbumname.disabled = false;
                while (table.firstChild) table.removeChild(table.firstChild);
            }
            return true;
        }


        function showDropDownList(s_uname) {
            if (s_uname != '') {

                var xh = CreateAjaxRequest();

                xh.send("showDropDownList=" + s_uname);

                if (xh.status != 200) {
                    alert("http error " + xh.status);
                    setTimeout(function() { document.write(xh.responseText); }, 10);
                    return;
                }
                document.write(xh.responseText); //get JSON objects
            }
            return true;
        }

        /**************************** end of uploader ***********************/
	
    </script>

    <script type="text/javascript">
        /*************************** NP ***************************/
        function saveOrder(action) {
            var data = new Array();
            var firstPhoto = '';
            if (action == "album") {
                $("#albumsContainer li").each(function(i, elm) {
                    data[i] = $(elm).attr("id").replace('album', '');
                });
            } else {
                $("#photosContainer li").each(function(i, elm) {
                    data[i] = $(elm).attr("id").replace('photo', '');
                });
                firstPhoto = $("#photosContainer li:first > div > img").attr('src');
            }

            $.ajax({
                type: "POST",
                url: "sortOrder.asp",
                data: "SortData=" + data + "&action=" + action,
                //contentType: "application/json; charset=utf-8",
                dataType: "text",
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                },
                complete: function(response) {
                    if (action == "photo") {
                        $('#album' + i_albumid + ' > div > img').attr('src', firstPhoto);
                    }
                }
            });
        };
        /****************************** End of NP ************************/
    </script>

    <script type="text/javascript" src="MainJS.js"></script>

    <%
	Dim objConn, objRSCustomers, objRSAlbums
	Dim strUserName, strSQL, strResults, strDiv
	Dim iCustID
	Dim albumID, icol, albumName, currentAlbumId
	Dim filePath
	filePath = "images/no_photo.jpg"
	strDiv = "photoDiv"
	Response.Expires = -1500    
	iCustID = Request.QueryString("custID")
	Set objConn = Server.CreateObject("ADODB.Connection")
	objConn.ConnectionString = "dsn=Developer;uid=JohnNgo;pwd=jo2.0G$!;"
	objConn.Open
	
	strSQL = "SELECT username FROM customers WHERE customerID = " & iCustID
	Set objRSCustomers = Server.CreateObject("ADODB.Recordset")
	objRSCustomers.Open strSQL, objConn
	Do While Not objRSCustomers.EOF
		strUserName = objRSCustomers("username")
		objRSCustomers.MoveNext
	Loop	
	objRSCustomers.Close
	set objRSCustomers = Nothing
	
	'========= Update - 21/11/2010 NP =======	
	'Select Albums with the first Photo 
	'=====================================
	strSQL =    "SELECT album.*,ISNULL(photo.FileName,'') AS FileName" &_
                " FROM PhotoAlbums as album" &_
                " LEFT JOIN Photos as photo" &_
                " ON (album.AlbumID = photo.AlbumID" &_
		        "     AND photo.PhotoID = ( SELECT TOP(1) PhotoID FROM Photos WHERE AlbumID = album.AlbumID ORDER BY Priority ASC)" &_
	            "    )" &_
                " WHERE RTRIM(album.username) = '" & Trim(strUserName) & "'" &_
                " ORDER BY Priority ASC"
	Set objRSAlbums = Server.CreateObject("ADODB.Recordset")
	objRSAlbums.Open strSQL, objConn
    %>
</head>
<body>
    <div id="menu">
        <ul>
            <li><a href="#photoAlbumDiv">Albums</a>
            </li>
            <li><a href="#photoDiv">Photos</a> </li>
        </ul>
    </div>
    <div class="clearer">
    </div>
    <div id="main-contener">
        <div id="photoAlbumDiv">
            <div id="addAlbumContainer" onclick="addAlbum('<%= strUserName %>')">
                    <div class="new-album1" style="text-align:center">
                    </div>
                    <input type='button' id="btAddAlbum" class="button gray" value='Add New Album' />
            </div>
            <ul id="albumsContainer">
                <%
						If Not objRSAlbums.EOF then			    	     
							Do While Not objRSAlbums.EOF				        	
								albumID = objRSAlbums("albumID")
								albumName = Server.HTMLEncode(objRSAlbums("albumName"))
								If Not objRSAlbums("FileName") = "" Then
								    filePath = "photos/" & objRSAlbums("username") & "/Thumbnails/" & objRSAlbums("FileName")
								Else
								    filePath = "images/no_photo.jpg"
								End If
								 			
                %>
                <li id="album<%= albumID %>" onmouseup="displayPhotos(<%= albumID %>,'<%= strUserName %>','photoDiv','<%= albumName %>');">
                    <div>
                        <img alt="" src='<%= filePath %>'  />
                    </div>
                    <span id="albumInfo<%= albumID %>">
                        <%= albumName%>
                    </span></li>
                <%	  
						    objRSAlbums.MoveNext
					        Loop
                %>
               
            </ul>
            
            <%  
						Else
							Response.Write "Not found!"
						End If
            %>
        </div>
        <div id="photoDiv">
            <div id="rename-album">
                <label for="album-name">
                    ALBUM:</label>
                <input type="text" id="albumName" />

                <input type="button" id="btRenameAlbum" value="Rename album" />
                <div id="msgRename" class="msg" style="display:none"> </div>
            </div>
            <div id="addAlbum">
                <div id="imageHolder">
                </div>
                <div id="buttonAddAlbum">
                    <input id="btnAddNewPhotos" type='button' class="button" value='+Add New Photo(s)' />
                </div>
            </div>
        </div>
        <div id="uploadDiv">
        </div>
        <div class="clearer">
        </div>
    </div>
    <div id="variable" style="display: none">
        <select id="albumsCombobox">
            <option value="">--- move to new album ---</option>
            <%
				    objRSAlbums.MoveFirst()
				    Do while not objRSAlbums.EOF
                          Response.Write "<OPTION VALUE = '" & objRSAlbums ("albumID") & "'>"
                          Response.Write objRSAlbums("albumName") & "</Option>"
                          objRSAlbums.MoveNext
                    loop
                    objRSAlbums.Close
				    set objRSAlbums = Nothing
					objConn.Close
				    set objConn = Nothing
            %>
        </select>
        <input type="hidden" id="isSortting" value="false" />
    </div>
    <!-- uploader -->
    <!--***VT***-->
    <div style="position: absolute; opacity:0.6;filter:alpha(opacity=60);
        width: 100%; background: black; height: 100%; visibility: hidden; top: 0px; left: 0px;
        z-index: 5;" id="oFilterDIV">
    </div>
    
    <!--************************** Uploader popup **********************-->
    <div id="UploaderDiv" style="position: absolute; top: 20px; left: 250px; visibility: hidden;
        width: 400px; height: 300px; background: black; z-index: 6; color: black">
        <table align="center" bgcolor="white" style="width: 100%" cellpadding="2px">
            <tr>
                <td style="color: white; background: black; font-family: arial; font-size: 12px;
                    font-weight: bold; text-align: center">
                    <table align="center" bgcolor="#CCCCCC" style="width: 100%">
                        <tr>
                            <td colspan="2" style="color: white; background: blue; font-family: arial; font-size: 12px;
                                font-weight: bold; width: 100%; height: 25px">
                                Upload Photos
                            </td>
                        </tr>
                        <tr>
                            <td width="40%" style="position:relative; padding:5px">
                                <table id="filelist" style='width:100%; border-collapse: collapse' class='Grid' border='0' cellspacing='0'
                                    cellpadding='2'>
                                </table>
                               <%

	                                        Dim uploader
	                                        Set uploader=new AspUploader
	                                        uploader.MaxSizeKB=10240
	                                        uploader.Name="myuploader"
	                                        uploader.MultipleFilesUpload=true
	                                        uploader.InsertText="Upload Photos"
	                                        uploader.AllowedFileExtensions="*.jpg,*.png,*.gif"
                                        	
                                        	uploader.ShowProgressBar=true 
                                            uploader.ShowProgressInfo=true 

	                                        uploader.InsertButtonID="uploadbutton"
	                                        uploader.ProgressCtrlID="uploaderprogresspanel"
	                                        uploader.ProgressTextID="uploaderprogresstext"
	                                        uploader.CancelButtonID="uploadercancelbutton"
                                        	
	

                                %>
                                <%= uploader.GetString() %>
                                <div id="uploaderprogresspanel" style='display: none; background-color: #CCCCCC;
                                    border: dashed 2px gray; padding: 4px;' bordercolor="Orange" borderstyle="dashed">
                                    <span id="uploaderprogresstext" style='color: firebrick'></span>
                                </div>
                                <input type="button" class="button" id="uploadercancelbutton" name="uploadercancelbutton" value="Cancel" />
                                
                                <!--************************** Message **********************-->
                                <div id="MessageDiv" style="padding:6px; display:none">
                                    <h2>Upload Complete!</h2>
                                </div>
                                <!--**************************End Message **********************-->
    
                                <input type="button" class="button" id="AddNewPhotos" name="AddNewPhotos" value="[Add New Photo(s) To Your Album?]"
                                    onclick="AddFilesToDB();" />
                            </td>
                            <td style="width: 60%; font-size: 9pt; text-align: left; color: Black; padding-left: 10px; padding-right: 10px">
                                <div id="uploadTip">
                                <br />
                                <br />
                                <br />
                                <br />
                                <b>Uploading Tip</b><br />
                                <br />
                                    You can select multiples photos in the dialog
                                    by holding the 'ctrl' key down while clicking on the photo.<br />
                                <br />
                                <br />
                                <br />
                                <br />
                                </div>
                            </td>
                        </tr>
                        <tr bgcolor="#999999">
                            <td colspan="2" width="80%" align="right">
                                <input type="button" class="button" id="uploadbutton" onclick="javascript:$('uploadTip').hide();" value="Upload Photos" />
                                <input type="button" class="button" id="closebutton" value="Close" onclick="closePopup_click('UploaderDiv');" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
    <!--************************** End Uploader popup **********************-->

    <script type="text/javascript">
        $(function() {

            $("#albumsContainer").sortable({
                cursor: 'move',
                start: function(event, ui) { $('#isSortting').val('true'); },
                stop: function(event, ui) {
                    $('#isSortting').val('false');
                    if (confirm("Do you want to save sort order?")) {
                        saveOrder('album');
                    } else {
                        $(this).sortable('cancel');
                    }
                }
            });

            $("#menu").tabs({
                select: function(event, ui) {
                    currentTab = ui.index;
                    cancelEdit(lastEditId, lastTitle, lastDescription, lastDateTaken);
                },
                selected: getQueryString("tabIndex")
            });
            var queryAlbumId = getQueryString("albumId");
            if (queryAlbumId != "") {
                document.getElementById("album" + queryAlbumId).onmouseup();
            }
        });               
    </script>

</body>
</html>
